/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jhu.profiteer.admin;

import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jhu.profiteer.data.LocationCommodity;
import jhu.profiteer.data.LocationCommodityJpaController;
import jhu.profiteer.data.LocationCommodityPK;
import jhu.profiteer.data.exceptions.NonexistentEntityException;
import jhu.profiteer.data.exceptions.PreexistingEntityException;

/**
 *
 * @author Jeremy
 */
public class LocationCommodityServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
      String submit = request.getParameter("submit");

      if(null == submit)
      {
        this.getServletContext()
                .getRequestDispatcher("/admin/loccoms")
                .forward(request, response);
        return;
      }

      HttpSession session = request.getSession();
      Vector<String> notices = (Vector<String>)session.getAttribute("notices");

      if(submit.equalsIgnoreCase("View Location Commodities"))
      {
        this.getServletContext()
                .getRequestDispatcher("/admin/loccom")
                .forward(request, response);
      }
      else if(submit.equalsIgnoreCase("Add Commodity to Location"))
      {
        this.getServletContext()
                .getRequestDispatcher("/admin/newLocCom")
                .forward(request, response);
      }
      else if(submit.equalsIgnoreCase("Create"))
      {
        boolean process = true;
        String locIdParam = request.getParameter("locationId");
        String url = "/admin/newLocCom";

        if((null == locIdParam) || locIdParam.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a location ID.");
          process = false;
        }

        String comIdParam = request.getParameter("commodityId");

        if((null == comIdParam) || comIdParam.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a commodity ID.");
          process = false;
        }

        String minParam = request.getParameter("minPrice");

        if((null == minParam) || minParam.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a minimum price.");
          process = false;
        }

        String maxParam = request.getParameter("maxPrice");

        if((null == maxParam) || maxParam.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a maximum price.");
          process = false;
        }

        if(process)
        {
          LocationCommodityJpaController lcjc = 
                  new LocationCommodityJpaController();

          Long locId = Long.parseLong(locIdParam);
          Long comId = Long.parseLong(comIdParam);

          if(lcjc.testForLocationCommodity(locId, comId))
          {
            if(null == notices) notices = new Vector<String>();
            notices.add("This location already has that commodity.");
            url = "/admin/loccom?locationId=" + locIdParam;
          }
          else
          {
            Long minPrice = Long.parseLong(minParam);
            Long maxPrice = Long.parseLong(maxParam);
            LocationCommodityPK lcpk = new LocationCommodityPK(locId, comId);
            LocationCommodity lc = new LocationCommodity();
            lc.setId(lcpk);
            lc.setMinPrice(minPrice);
            lc.setMaxPrice(maxPrice);

            try
            {
              lcjc.create(lc);
              if(null == notices) notices = new Vector<String>();
              notices.add("Successfully created location commodity.");
              url = "/admin/loccom?locationId=" + locIdParam;
            } catch (PreexistingEntityException ex) {
              if(null == notices) notices = new Vector<String>();
              notices.add("That location commodity already exists.");
            } catch (Exception ex) {
              if(null == notices) notices = new Vector<String>();
              notices.add("Error creating location commodity.");
            }
          }
        }

        session.setAttribute("notices", notices);
        this.getServletContext()
                .getRequestDispatcher(url)
                .forward(request, response);
      }
      else if(submit.equalsIgnoreCase("Edit"))
      {
        this.getServletContext()
                .getRequestDispatcher("/admin/newLocCom")
                .forward(request, response);
      }
      else if(submit.equalsIgnoreCase("Update"))
      {
        boolean process = true;
        String locIdParam = request.getParameter("locationId");
        String url = "/admin/newLocCom";

        if((null == locIdParam) || locIdParam.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a location ID.");
          process = false;
        }

        String comIdParam = request.getParameter("commodityId");

        if((null == comIdParam) || comIdParam.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a commodity ID.");
          process = false;
        }

        String minParam = request.getParameter("minPrice");

        if((null == minParam) || minParam.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a minimum price.");
          process = false;
        }

        String maxParam = request.getParameter("maxPrice");

        if((null == maxParam) || maxParam.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a maximum price.");
          process = false;
        }

        if(process)
        {
          LocationCommodityJpaController lcjc =
                  new LocationCommodityJpaController();
          Long locId = Long.parseLong(locIdParam);
          Long comId = Long.parseLong(comIdParam);
          LocationCommodity lc = lcjc.findLocationCommodity(locId, comId);
          Long minPrice = Long.parseLong(minParam);
          Long maxPrice = Long.parseLong(maxParam);
          lc.setMinPrice(minPrice);
          lc.setMaxPrice(maxPrice);

          try
          {
            lcjc.edit(lc);
            if(null == notices) notices = new Vector<String>();
            notices.add("Successfully updated location commodity.");
          } catch (NonexistentEntityException ex) {
            if(null == notices) notices = new Vector<String>();
            notices.add("That location commodity no longer exists.");
          } catch (Exception ex) {
            if(null == notices) notices = new Vector<String>();
            notices.add("Error updating location commodity.");
          }
        }

        session.setAttribute("notices", notices);
        this.getServletContext()
                .getRequestDispatcher(url)
                .forward(request, response);
      }
      else if(submit.equalsIgnoreCase("Delete"))
      {
        boolean process = true;
        String locIdParam = request.getParameter("locationId");

        if((null == locIdParam) || locIdParam.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a location ID.");
          process = false;
        }

        String comIdParam = request.getParameter("commodityId");

        if((null == comIdParam) || comIdParam.isEmpty())
        {
          if(null == notices) notices = new Vector<String>();
          notices.add("You must supply a commodity ID.");
          process = false;
        }

        if(process)
        {
          LocationCommodityJpaController lcjc =
                  new LocationCommodityJpaController();
          Long locId = Long.parseLong(locIdParam);
          Long comId = Long.parseLong(comIdParam);

          try
          {
            lcjc.destroy(locId, comId);
            if(null == notices) notices = new Vector<String>();
            notices.add("Successfully deleted location commodity.");
          }
          catch (NonexistentEntityException ex)
          {
            if(null == notices) notices = new Vector<String>();
            notices.add("Could not delete - commodity no longer exists.");
          }
        }

        session.setAttribute("notices", notices);
        this.getServletContext()
                .getRequestDispatcher("/admin/loccom?locationId=" + locIdParam)
                .forward(request, response);
      }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
